package item22;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author Lv Jing
 * @date 2018年08月02日 22:39
 */
public class FindKthToTail {

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public class Solution {
        public ListNode FindKthToTail(ListNode head, int k) {
            if (head == null || k <= 0) {
                return null;
            }

            ListNode pre = head;
            ListNode last = head;
            // 先把pre指针向后移动k次。这样pre再移动到最后的次数就是last从头开始移动到的位置，刚好就是倒数第k个节点
            for (int i = 1; i <= k; i++) {
                if (pre != null) {
                    pre = pre.next;
                } else {
                    return null;
                }
            }
            while (pre != null) {
                last = last.next;
                pre = pre.next;
            }
            return last;
        }
    }

    @Test
    public void test01() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null)))));
        ListNode last = new Solution().FindKthToTail(head, 6);
        Assert.assertEquals(null, last);
    }
}
